<?php

namespace Modules\Api\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use Modules\common\Http\Controllers\ApiController;
use Modules\common\Entities\User as UserModel;

class UserController extends ApiController
{
    public function __construct()
    {
        
    }

    /**
     * 注册
     */
    public function register(Request $request)
    {
        //判断是不是post提交
        if($request->method("post"))
        {
            //判断数据是否合法
            $validator = Validator::make($request->all(),[

                "phone"=>"required|unique:user|max:11|min:11",

                "password"=>"required|min:6|confirmed",

                // "salt"=>"required|max:10|min:10"
            ]);
            
            //判断提交过来的数据是否合法
            if($validator->fails())
            {
                // 不合法返回错误信息
                return $this->failure($validator->errors()->first());
    
            }

            //判断用户是否存在
            $user = UserModel::where(["phone"=>$request->input("phone")])->first();

            if($user)
            {
                return $this->failure("手机号已被注册");
            }


            // 生成密码盐
            $salt = substr(md5(time()),0,10);

            // 组装数据
            $data = [

                "phone"=>$request->input("phone"),

                "password"=>md5($salt.$request->input("password")),

                "salt"=>$salt

            ];

            // 、、插入数据
           $result =  UserModel::create($data);

           if($result === NULL)
           {
                return $this->failure("注册失败");
           }

           return $this->prosperity("注册成功");
        }   

    } 
    
    /**
     * 登录
     */
    public function login(Request $request)
    {
        //判断是不是post提交
        if($request->method("post"))
        {
            //判断数据是否合法
            $validator = Validator::make($request->all(),[

                "phone"=>"required|max:11|min:11",

                "password"=>"required|min:6",

            ]);
            
            //判断提交过来的数据是否合法
            if($validator->fails())
            {
                // 不合法返回错误信息
                return $this->failure($validator->errors()->first());
    
            }

            //判断用户是否存在
            $user = UserModel::where(["phone"=>$request->input("phone")])->first();

            if(!$user)
            {
                return $this->failure("用户不存在");
            }

            // 用户存在，判断密码是否正确
            $userPassword = md5($user["salt"].$request->input("password"));

            if($userPassword != $user["password"])
            {
                return $this->failure("密码错误");
            }

            // 密码正确 返回用户信息
            unset($user["password"]);
            unset($user["salt"]);
            return $this->prosperity("登录成功",$user);
        }      
    }

}
